﻿using System;
using System.Diagnostics;
using System.IO;
using Microsoft.Build.Utilities;

namespace MethodCaching.Tests
{
    public static class AssemblyVerifier
    {
        public static void Verify(string filename)
        {
            string peverifyPath = GetPeverifyPath();
            var startInformation = new ProcessStartInfo(peverifyPath);
            startInformation.CreateNoWindow = true;
            startInformation.Arguments = "\"" + filename + "\" /MD /IL /UNIQUE /VERBOSE";
            startInformation.RedirectStandardOutput = true;
            startInformation.UseShellExecute = false;            
            var process = new Process {StartInfo = startInformation};
            process.Start();
            var processOutput = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            var result = string.Format("PEVerify Exit Code: {0}", process.ExitCode);
            Console.WriteLine(result);
            if (process.ExitCode == 0)
                return;
            Console.WriteLine(processOutput);
            throw new BadImageFormatException(processOutput);
        }

        private static string GetPeverifyPath()
        {
            return Path.Combine(ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version40),
                                @"bin\NETFX 4.0 Tools\peverify.exe");
        }
    }
}
